/******************************* Calendar Start ******************************/
function TaskCalendarCtrl($scope, $dialog, $routeParams, DataCenter, Util, $filter) {
    var now = new Date();
    var today = Date.begin_of_date(new Date());
    var d = today.getDate(), m = today.getMonth(), y = today.getFullYear();
    var format_event = function (task) {
        var desc = task.description;
        var event = {
            "id": task.id,
            "title": task.name,
            "start": desc.split("##")[0],
            "task": task.task,
            "kwargs": task.kwargs,
            "queue": task.queue,
            "description": desc.split("##")[1],
            "hide": false,
            "allDay": true
        }
        return event;
    }
    $scope.events = [];
    $scope.event_sources = [$scope.events];

    $scope.priorities = [
        {name: '全部', value: -1},
        {name: '一般', value: 0},
        {name: '普通', value: 1},
        {name: '高级', value: 2},
        {name: '紧急', value: 3}
    ];
    $scope.search = {priority: -1};

    DataCenter.tasks({id: $routeParams.id, scope: 'all'}, function (events) {
        angular.forEach(events.data, function (v) {
            var e = format_event(v);
            $scope.events.push(e);
        });
    });

    $scope.switch_level = function (priority) {
        angular.forEach($scope.events, function (e) {
            if (priority == -1) {
                e.hide = false;
                return;
            }
            if (e.priority == priority) {
                e.hide = false;
            } else {
                e.hide = true;
            }
        });
        $scope.current_calendar.fullCalendar('rerenderEvents');
    };

    $scope.add_task = function () {
        open_dialog(now, null);
    };

    $scope.day_click = function (date, all_day, js_event, view) {
        if (date >= today) {
            var now = new Date();
            date.setHours(now.getHours());
            date.setMinutes(now.getMinutes());
            date.setSeconds(now.getSeconds());
            $scope.$apply(function () {
                open_dialog(date, null);
            });
        }
    };

    $scope.event_on_drop = function (event, day_delta, minute_delta, all_day, revert_func, js_event, ui, view) {
        event.dropevent = true;
        if(event.start<=new Date()){
            Util.alert("任务时间应晚于当前时间");
            revert_func();
            return false;
        }
        event.start2 = $filter('date')(event.start, 'yyyy-MM-dd HH:mm:ss')
        DataCenter.update_schedule_task({id: $scope.datacenter.id, task: event}, function (data) {
            if (data.status == '200') {
                event.id = data.newid
                return;
            } else {
                revert_func();
                Util.alert("修改任务失败");
                return false;
            }
        },function(){
            revert_func();
            Util.alert("修改任务失败");
            return false;
        });
    };

    $scope.event_on_resize = function (event, day_delta, minute_delta, revert_func, js_event, ui, view) {
        $scope.$apply(function () {
            $scope.alert_message = ('Event Resized to make dayDelta ' + minute_delta);
        });
    };

    $scope.edit_task = function (cal_event, e, view) {
        $scope.$apply(function () {
            open_dialog(today, cal_event);
        });
    };

    $scope.remove = function (index, e) {
        remove_event($scope.events, e);
    };


    $scope.change_view = function (view) {
        $scope.current_calendar.fullCalendar('changeView', view);
    };

    $scope.ui_config = {
        calendar: {
            height: 450,
            editable: true,
            ignoreTimezone: false,
            header: {
                left: '',
                center: 'title',
                right: 'month basicWeek basicDay prev,next'
            },

            // time formats
            titleFormat: {
                month: 'MMMM yyyy',
                week: "MMMd - {MMMd}",
                day: 'dddd, MMMd, yyyy'
            },
            columnFormat: {
                month: 'ddd',
                week: 'ddd M/d',
                day: 'dddd M/d'
            },
            timeFormat: { // for event elements
                '': 'h(:mm)t' // default
            },

            // locale
            isRTL: false,
            firstDay: 0,
            monthNames: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
            monthNamesShort: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
            dayNames: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
            dayNamesShort: ['日', '一', '二', '三', '四', '五', '六'],
            buttonText: {
                prev: '&nbsp;&#9668;&nbsp;',
                next: '&nbsp;&#9658;&nbsp;',
                prevYear: '&nbsp;&lt;&lt;&nbsp;',
                nextYear: '&nbsp;&gt;&gt;&nbsp;',
                today: '今天',
                month: '月',
                week: '星期',
                day: '天'
            },
            dayClick: $scope.day_click,
            eventDrop: $scope.event_on_drop,
            eventResize: $scope.event_on_resize,
            eventClick: $scope.edit_task,
            eventRender: function (event, element) {
                var clazz = "event_at_3";
                if (event.start < now) {
                    clazz = "event_expired";
                }
                if (event.hide) {
                    element.addClass("hide");
                } else {
                    element.removeClass("hide");
                }
                element.addClass(clazz).find('span.fc-event-title').append('<span class="pull-right"><i class="icon-pencil"></i><i class="icon-trash"><i></span>');
                element.on('click', '.icon-trash', function (e) {
                    if (window.confirm("你真的确定要删除这个事件吗?")) {
                        DataCenter.delete_schedule_task({id: $scope.datacenter.id, taskid: event.id}, function (data) {
                            if (data.status == "200") {
                                $scope.remove(-1, event);
                            }
                        });
//            $scope.$apply(function(){
//              $scope.remove(-1, event);
//            });
                    }
                    e.stopPropagation();
                });
            }
        }
    };

    function remove_event(c, e) {
        var index = -1;
        for (var i = 0; i < c.length; i++) {
            if (e.id == c[i].id) {
                index = i;
                break;
            }
        }
        if (index >= 0) {
            c.splice(index, 1);
        } else {
            alert("你所选的事件不存在");
        }
    }

    function open_dialog(date, event) {
        $scope.selected_event = event;
        $scope.selected_date = date;

        Util.dialog("/static/partials/datacenters/_task.html", 'TaskCalendarDialogCtrl', $scope, {backdropClick: false, dialogClass: 'modal mini'});
    }
}

function TaskListCtrl($scope, $routeParams, DataCenter, Util) {
    $scope.page_size = 15;
    $scope.service = function (start, limit) {
        DataCenter.tasks({id: $routeParams.id, current_page: start, page_size: limit}, function (events) {
//            $scope.tasks = events.data;
            $scope.tasks = []
            angular.forEach(events.data, function (v) {
                var e = format_task(v);
                $scope.tasks.push(e);
            });
            $scope.total_page = events.total_page;
            $scope.total_count = events.total_count;
        });
    }
    Util.paginate($scope, 'events');

    $scope.delete = function(index){
        task = $scope.tasks[index];
        if (window.confirm("你真的要删除这个任务吗?")) {
            DataCenter.delete_schedule_task({id: $scope.datacenter.id, taskid: task.id}, function (data) {
                if (data.status == "200") {
                    remove_event($scope.tasks, task);
                }
            });
        }
    }

    function format_task(task){
        tasks = {"shutdown_vm":"关机","start_vm":"开机","reboot_vm":"重启","snapshot_vm":"快照","snapshot_restore":"快照还原","delete_vm":"删除"}
        args = eval('('+task.kwargs+')')
        taskname = tasks[args.task_name]
        var desc = task.description;
        var event = {
            "id": task.id,
            "title": task.name,
            "start": desc.split("##")[0],
            "task": taskname,
            "description": desc.split("##")[1]
        }
        return event;
    }

    function remove_event(c, e) {
        var index = -1;
        for (var i = 0; i < c.length; i++) {
            if (e.id == c[i].id) {
                index = i;
                break;
            }
        }
        if (index >= 0) {
            c.splice(index, 1);
        } else {
            alert("你所选的事件不存在");
        }
    }
}

/******************************* Calendar End ******************************/

/******************************* VM Action Start ******************************/
function VMMgmtCtrl($rootScope, $scope, $routeParams, DataCenter, Cluster, Host, Util, $pollingPool, VM) {
    $scope.selected || ($scope.selected = {});
    $scope.page_size = 10;
    var resource = {};
    if ($scope.current_target_type == 'DataCenter') {
        resource = DataCenter;
    } else if ($scope.current_target_type == 'Cluster') {
        resource = Cluster;
    } else if ($scope.current_target_type == 'Host') {
        resource = Host;
    } else {
        resource.vms = VM.get;
    }
    $scope.selectvm = function (m) {
        $scope.selected_vm = m;
    }
//  $scope.check_click = function(m){
//        $scope.selected[m.id] = m;
//    }
    $scope.service = function (start, limit) {
        resource.vms({id: $routeParams.id, current_page: start, page_size: limit}, function (vms) {
            $scope.vms = vms.data || [vms];//为了兼容VM.get方法
            $scope.total_page = vms.total_page;
            $scope.total_count = vms.total_count;
        });
    };
    var job;
    $scope.$watch('vms', function (newvalue) {
        if (newvalue) {
            console.log('restart vms interval job');
            if (job) job.cancel();
            job = $pollingPool.add(function () {

                var vm_ids = $scope.vms.map(function (vm) {
                    return vm.id
                });
                var ids = vm_ids.join(',');
                VM.status({ids: ids}, function (data) {
                    Util.update($scope.vms, data);
                }, function (e) {
                    console.log('vm status got :' + e.data)
                });
            }, 5000);
        }
    })
    Util.paginate($scope, 'vms');

    //til.pagination($scope, 'vms', 5);

    $scope.link_vnc = function (vm) {
        open_vnc(vm, $rootScope,Util);
    }

}

function open_vnc(vm, $rootScope,Util) {

    if (vm.status == 'running') {
        var port = 5900 + parseInt(vm.id);
        var parameter = "host=" + vm.host.ip + "&port=" + port+"&password="+vm.remote_password;

        if(!$rootScope.vnc_conns){
            $rootScope.vnc_conns = [];
        }
        var newurl = {vnc_url : "/static/partials/ssh/vnc.html?" + parameter,id:vm.id};
        var clone_conns = angular.copy($rootScope.vnc_conns);
        var newconn = true;
        for(var i=0;i<clone_conns.length;i++){
            if(clone_conns[i].vnc_url == newurl.vnc_url){
                $rootScope.vnc_conns[i] = newurl;
                newconn = false;
                break;
            }
        }
        if (newconn){
            $rootScope.vnc_conns.push(newurl);
        }else{
            // 刷新iframe
            var f = document.getElementById('iframe_vnc'+port);
            f.contentWindow.location.reload(true);
        }

    } else {
        Util.alert('虚拟机没有开机!');
    }

}

function ClusterVMMgmtCtrl($scope, $routeParams, Cluster, Util) {
    $scope.selected || ($scope.selected = {});
    $scope.page_size = 5;
    $scope.service = function (start, limit) {
        Cluster.vms({id: $routeParams.id, current_page: start, page_size: limit}, function (vms) {
            $scope.vms = vms.data;
            $scope.total_page = vms.total_page;
            $scope.total_count = vms.total_count;
        });
    };

    Util.paginate($scope, 'vms');

    //til.pagination($scope, 'vms', 5);
}

function VMActionBarCtrl($scope, $q, VM, Util, $pollingPool, ztree, Shortcut) {
    $scope.min_msg = "你至少应该选择{0}台虚拟机."
    $scope.max_msg = "你不能选择超过{0}台虚拟机."

    function handle_activity(vm_ids, vms, data, status) {
        $pollingPool.add_activity_callback(data.activity, function () {
            angular.forEach(vms, function (item) {
                if (vm_ids.indexOf(item.id) != -1) {
                    item.status = status;
                }
            })
        })
    }

    $scope.do_create = function () {
//    $scope.selected_vm = null;
        VM.authcheck(function(){
            Util.dialog("vm_workflow.html", 'VMWorkflowDialogCtrl', $scope, {backdropClick: false});
        },function(data){
            Util.alert(Util.decode_error_msg(data.data));
        })
    };

    $scope.do_edit = function () {
        if (!$scope.selected_vm) {
            Util.alert('请选择虚拟机');
            return;
        }
        Util.dialog("/static/partials/vms/vm_config.html", 'VMConfigDialogCtrl', $scope, {backdropClick: false});
    };

    $scope.do_delete = function () {
        if(!Util.check_records($scope, 'vms', 1, 100)){
            return;
        }
        Util.bind($scope, 'vms').select(1, 100).confirm("你确定要删除它们吗，此操作将无法恢复!").then(function (vms) {
            var vm_ids = vms.map(function (vm) {
                return vm.id;
            });
            console.log("DELETE ALL VMS " + vm_ids);
            VM.delete({ids: vm_ids}, function (data) {

                $pollingPool.add_activity_callback(data.activity, function () {
                    // 删除虚拟机成功后，将在此虚拟机详细页面中生成的书签也同步删除
                    Shortcut.delete_from_thrd({ids: vm_ids, type: 'vm'});

                    angular.forEach(vms, function (vm) {
                        var index = $scope.vms.indexOf(vm);
                        $scope.vms.splice(index, 1);
                        ztree.deletenode('v' + vm.id);
                    });


                });

            });
        });
    };

    $scope.do_template = function () {
//    Util.bind($scope, 'vms').select(1, 1).then(function(vms){
//      $scope.selected_vm = vms[0];
        if (!$scope.selected_vm) {
            Util.alert('请选择虚拟机');
            return;
        }
        var disks = $scope.selected_vm.vdisk_set.filter(function(disk){
            return disk.device_type != 'cdrom';
        })
        if(disks && disks[0].storage.protocol == 'iscsi'){
            Util.alert('虚拟机系统磁盘为iscsi存储，不能存为模板');
            return;
        }
        if ($scope.selected_vm.status != "shutdown") {
            Util.alert('请先关闭虚拟机');
        } else
            Util.dialog("/static/partials/vms/template_dialog.html", 'SaveAsTemplateDialogCtrl', $scope, {backdropClick: false, dialogClass: 'modal mini'});
//    });
    };


    $scope.do_migrate = function () {
//    Util.bind($scope, 'vms').select(1, 1).then(function(vms){
//      $scope.selected_vm = vms[0];
        if (!$scope.selected_vm) {
            Util.alert('请选择虚拟机');
            return;
        }
        if ($scope.selected_vm.status != 'running') {
            Util.alert('只能迁移活动的虚拟机');
        } else
            Util.dialog("/static/partials/vms/migrate_dialog.html", 'VMMigrateDialogCtrl', $scope, {backdropClick: false, dialogClass: 'modal mini'});
//    });
    };

    $scope.do_suspend = function () {
        Util.bind($scope, 'vms').select(1, 100).confirm("你确定要暂停它(们)吗!").then(function (vms) {
            var vm_ids = vms.map(function (vm) {
                return vm.id;
            });
            console.log("Suspend VMS " + vm_ids);
            VM.suspend({ids: vm_ids}, function (data) {
                handle_activity(vm_ids, vms, data, 'paused');
            })
        });
    };

    $scope.do_start = function () {
        Util.bind($scope, 'vms').select(1, 100).confirm("你确定要启动它(们)吗？").then(function (vms) {
            var vm_ids = vms.map(function (vm) {
                return vm.id;
            });
            console.log("Start VMS " + vm_ids);
            VM.start({ids: vm_ids}, function (data) {
                handle_activity(vm_ids, vms, data, 'running');
            });
        });
    };

    $scope.do_reboot = function () {
        Util.bind($scope, 'vms').select(1, 100).confirm("你确定要重启它(们)吗？").then(function (vms) {
            var vm_ids = vms.map(function (vm) {
                return vm.id
            });
            console.log("Restart VMS " + vm_ids);
            VM.reboot({ids: vm_ids}, function (data) {
                console.log('reboot vms successful');
            });
        });
    };

    $scope.do_shutdown = function () {
        Util.bind($scope, 'vms').select(1, 100).confirm("你确定要关闭它(们)吗").then(function (vms) {
            var vm_ids = vms.map(function (vm) {
                return vm.id
            });
            console.log("Shutdown VMS " + vm_ids);
            VM.soft_shutdown({ids: vm_ids}, function (data) {
                console.log('soft_shutdown vms successful');//soft shutdown we do not update status
            });
        });
    };

    $scope.do_force_shutdown = function () {
        Util.bind($scope, 'vms').select(1, 100).confirm("你确定要关闭它(们)吗").then(function (vms) {
            var vm_ids = vms.map(function (vm) {
                return vm.id
            });
            console.log("Shutdown VMS " + vm_ids);
            VM.shutdown({ids: vm_ids}, function (data) {
                handle_activity(vm_ids, vms, data, 'shutdown');
            });
        });
    };

    $scope.do_snapshot = function () {

        if ($scope.selected_vm.vdisk_set.some(function(disk){
            return disk.storage&&disk.storage.protocol == 'iscsi';
        })){
            Util.alert('虚拟机包含iscsi磁盘，不支持快照操作!');
            return;
        }

        Util.bind($scope, 'vms').select(1, 1).then(function (vms) {
            $scope.selected_vm = vms[0];
//            if ($scope.selected_vm.status != "running") {
//                Util.alert('请先启动虚拟机');
//            } else
                Util.dialog("/static/partials/vms/snapshot_dialog.html", 'SnapshotDialogCtrl', $scope, {backdropClick: false, dialogClass: 'modal mini'});
        });
    };

    $scope.do_restore_snapshot = function () {
//    Util.bind($scope, 'vms').select(1, 1).confirm("当前数据会直接丢弃掉,确定要恢复快照?").then(function(vms){
//      $scope.selected_vm = vms[0];
        if (!$scope.selected_vm) {
            Util.alert('请选择虚拟机');
            return;
        }
        Util.dialog("/static/partials/vms/restore_snapshot_dialog.html", 'SnapshotRestoreDialogCtrl', $scope, {backdropClick: false, dialogClass: 'modal mini'});
//    });
    };


    $scope.do_unsuspend = function () {
        Util.bind($scope, 'vms').select(1, 100).then(function (vms) {
            var vm_ids = vms.map(function (vm) {
                return vm.id
            });
            console.log("operation VMS " + vm_ids)
            VM.unsuspend({ids: vm_ids}, function (data) {
                handle_activity(vm_ids, vms, data, 'running');
            })
        });
    };


    $scope.do_hibernate = function () {
        Util.bind($scope, 'vms').select(1, 100).confirm("你确定要休眠吗").then(function (vms) {
            var vm_ids = vms.map(function (vm) {
                return vm.id
            });
            console.log("operation VMS " + vm_ids)
            VM.hibernate({ids: vm_ids}, function (data) {
                handle_activity(vm_ids, vms, data, 'saved');
            })
        });
    };

    $scope.do_clone = function () {

        VM.authcheck(function(){
            if (!$scope.selected_vm) {
                Util.alert('请选择要克隆的虚拟机');
                return;
            }
            var hasblock = $scope.selected_vm.vdisk_set.some(function(disk){
                return disk.storage && disk.storage.protocol == 'iscsi';
            });

            if (hasblock){
                Util.alert('虚拟机包含iscsi磁盘，不支持克隆操作!');
                return;
            }

            if($scope.selected_vm.snapshot_set.length>0 && $scope.selected_vm.status!='shutdown'){
                Util.alert('拥有快照的虚拟机只能在关机状态下进行克隆操作!');
                return;
            }

            Util.dialog("/static/partials/vms/_vm_clone.html", 'VMCloneDialogCtrl', $scope, {backdropClick: false, dialogClass: 'modal mini'});
        },function(data){
            Util.alert(Util.decode_error_msg(data.data));
            return;
        })

    };

}
/******************************* VM Action End *****************************/

/******************************* Host Action Start ******************************/
function HostMgmtCtrl($scope, $routeParams, DataCenter, Cluster, Util, $pollingPool, Host, $rootScope) {
    var resource = $scope.current_target_type == 'DataCenter' ? DataCenter : Cluster;
    $scope.selected || ($scope.selected = {});
    $scope.page_size = 5;
    $scope.service = function (start, limit) {
        resource.hosts({id: $routeParams.id, current_page: start, page_size: limit}, function (hosts) {
            $scope.hosts = hosts.data;
            $scope.total_page = hosts.total_page;
            $scope.total_count = hosts.total_count;
            check_host_status();
        });
    };
    function check_host_status() {
        //操作远程管理卡时不需要更新主机状态
        if (!$rootScope.runpowertool) {
            var host_ids = $scope.hosts.map(function (host) {
                return host.id
            });
            Host.status({ids: host_ids.join(',')}, function (data) {
                Util.update($scope.hosts, data);

            });
        }

    }

    var job;
    $scope.$watch('hosts', function (newvalue) {
        if (newvalue) {
            console.log('restart hosts interval job');
            if (job) job.cancel();
            job = $pollingPool.add(function () {
                check_host_status();
            }, 10000);
        }

    })

    Util.paginate($scope, 'hosts');

    $scope.link_ssh = function (host) {

        var parameter = "host=" + host.ip + "&port=" + host.port + "&username=" + host.username + "&password=" + host.password;

        var width = 675;
        var height = 375;
        var wt = (screen.width - width) / 2;
        var wl = (screen.height - height) / 2;

        var win = window.open("/static/partials/ssh/ssh.html?" + parameter,
            "ssh", "scrollbars=no,height=375,width=675,top=" + wl + ",left=" + wt);
    }

    $scope.selected_host = null;
    $scope.show_details = function () {
        $scope.selected_host = this.host;
        $scope.selected_host.running_vms = $.grep(this.host.instance_set, function (item) {
            return item.status == 'running';
        })

    };
}

//主机列表工具栏
function HostActionBarCtrl($scope, $dialog, Host, Util, $rootScope) {

    $scope.min_msg = "你至少应该选择{0}台主机."
    $scope.max_msg = "你不能选择超过{0}台主机."

    $scope.do_edit = function () {
        Util.dialog("/static/partials/hosts/_activate_form.html", 'HostUpsertDialogCtrl', $scope,
            {backdropClick: false, dialogClass: 'modal mini2 top'});
    };

    $scope.do_remove = function () {
        Util.confirm("你确定要移除主机吗，此操作将无法恢复!", function () {
            $scope.selected_host.deleted = true;
            Host.remove({id: $scope.selected_host.id}, angular.noop, function (data) {
                $scope.selected_host.deleted = false;
            })
        })

    };

    $scope.do_maintain = function () {
//    Util.bind($scope, 'hosts').select(1, 100).confirm('确定要进行维护操作？').then(function(hosts){
//      var host_ids = hosts.map(function(host){ return host.id; });
//      console.log("Maintain the hosts " + host_ids);
//      new Host({ids: host_ids}).$maintain(Util.update_activities);
//    });
    };

    $scope.do_activate = function () {
        Util.dialog("/static/partials/hosts/_activate_form.html", 'HostActivateDialogCtrl', $scope, {backdropClick: false, dialogClass: 'modal mini2 top'});
    };


    function check_power_card($scope) {
        if (!$scope.selected_host.powertool) {
            Util.alert("此服务器没有安装远程管理卡！");
            return false;
        }
        return true;
    }

    var do_power_action = function (action, msg, deststatus) {
        if (check_power_card($scope)) {
            var id = $scope.selected_host.id;
            var originstatus = $scope.selected_host.status;
            $rootScope.runpowertool = true;//阻止host状态自动更新
            $scope.selected_host.status = 4;
            Host[action]({id: id}, function () {
                Util.alert(msg + "服务器成功！");
                $scope.selected_host.status = deststatus;
                $rootScope.runpowertool = false;
            }, function () {
                $scope.selected_host.status = originstatus;
                Util.alert(msg + "服务器失败！");
                $rootScope.runpowertool = false;
            });
        }
    }
    $scope.do_start = function () {
        do_power_action('start', "启动", 2)
    };

    $scope.do_shutdown = function () {
        do_power_action('shutdown', "关闭", 3)
    };

    $scope.do_reboot = function () {
        do_power_action('reboot', "重启", 2)
    };

}

/******************************* Host Action End ******************************/

function ClusterDiskMgmtCtrl($scope, Cluster, $routeParams, Util, VM, $pollingPool) {
    $scope.page_size = 5;

    $scope.selectdisk = function () {
        $scope.selected_disk = this.vdisk;
        $scope.vm = $scope.selected_disk.instance;
    }

    $scope.service = function (start, limit) {
        Cluster.vdisks({id: $routeParams.id, current_page: start, page_size: limit}, function (data) {
            $scope.vdisks = data.data;
            $scope.total_page = data.total_page;
            $scope.total_count = data.total_count;
        });
    };

    Util.paginate($scope, 'vdisks');
    $scope.fromcluster = true;
    $scope.do_add = function () {
        $scope.vm = {host: {cluster: {id: $routeParams.id }}};//mock vm data for newdisk_config_ctrl
        $scope.title = "修改虚拟机磁盘";
        $scope.hasvdisk = false;

        Util.dialog("/static/partials/vms/new_disk.html", "newdisk_config_ctrl", $scope, {backdropClick: false, dialogClass: 'modal mini'});
    }


    $scope.update_disk = function () {
        $scope.title = "创建虚拟机磁盘";
        Util.dialog("/static/partials/vms/new_disk.html", "update_disk_ctrl", $scope, {backdropClick: false, dialogClass: 'modal mini'});
    }


    $scope.delete_disk = function () {
        //如果是游离的磁盘我们调用cluster.delete_disk，如果是已经关联的磁盘，我们调用VM.delete_disk
        var resource = Cluster;
        if ($scope.selected_disk.instance) {
            resource = VM
        }
        Util.confirm('确定要删除吗?', function () {
            delete_disk(resource, $scope, $pollingPool, true);
        })
    }

    $scope.detach_disk = function () {
        //解除操作delete_disk中使用的id参数永远是vm.id,所以这里要mock vm id参数
        $scope.vm.id = $scope.selected_disk.instance.id;
        Util.confirm('确定要和虚拟机解除关联吗?解除后虚拟机将不再使用当前磁盘', function () {
            delete_disk(VM, $scope, $pollingPool, false);
        })
    }

    $scope.attach_disk = function () {
        Util.dialog("/static/partials/clusters/attach_vdisk.html", "attach_disk_ctrl", $scope, {backdropClick: false, dialogClass: 'modal mini'});
    }


}
